package cluster

import (
	"errors"
	"os"

	"gopkg.openfuyao.cn/bkecommon"
	configv1beta1 "gopkg.openfuyao.cn/bkecommon/cluster/api/v1beta1"
	configinit "gopkg.openfuyao.cn/bkecommon/cluster/initialize"
	"gopkg.openfuyao.cn/bkecommon/security"
	yaml2 "sigs.k8s.io/yaml"
)

func NewBKEClusterFromFile(file string) (*configv1beta1.BKECluster, error) {
	conf := &configv1beta1.BKECluster{}
	yamlFile, err := os.ReadFile(file)
	if err != nil {
		return nil, err
	}
	err = yaml2.Unmarshal(yamlFile, conf)
	if err != nil {
		return nil, err
	}
	if conf.Spec.ClusterConfig == nil {
		return nil, errors.New("The cluster configuration cannot be empty. ")
	}

	bc, err := configinit.NewBkeConfigFromClusterConfig(conf.Spec.ClusterConfig)
	if err != nil {
		return nil, err
	}
	err = bc.Validate()
	if err != nil {
		return nil, err
	}

	newNodes := []configv1beta1.Node{}
	for _, node := range bc.Nodes {
		tmpNode := node
		_, err = security.AesDecrypt(node.Password)
		if err == nil {
			newNodes = append(newNodes, tmpNode)
			continue
		}
		p, err := security.AesEncrypt(node.Password)
		if err != nil {
			return nil, err
		}
		tmpNode.Password = p
		newNodes = append(newNodes, tmpNode)
	}
	bc.Nodes = newNodes

	conf.Spec.ClusterConfig, _ = configinit.ConvertBkEConfig(bc)
	if conf.Spec.ClusterConfig.CustomExtra == nil {
		conf.Spec.ClusterConfig.CustomExtra = map[string]string{
			bkecommon.BKEAgentListenerAnnotationKey: bkecommon.BKEAgentListenerCurrent,
		}
	} else {
		if len(conf.Spec.ClusterConfig.CustomExtra[bkecommon.BKEAgentListenerAnnotationKey]) == 0 {
			conf.Spec.ClusterConfig.CustomExtra[bkecommon.BKEAgentListenerAnnotationKey] = bkecommon.BKEAgentListenerCurrent
		}
	}
	return conf, nil
}
